<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src = "bower_components/angular/angular.js"></script>
	<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body ng-app="mainApp" ng-controller="userCtrl">
<div>
	<h1>User List</h1>
	<table class="table">
		<tr ng-repeat="u in users">
			<td>{{u.uname}}</td>
			<td>{{u.age}}</td>
			<td><button class="btn btn-primary" ng-click="edit($index)">edit</button></td>
			<td><button class="btn btn-success" ng-click="delete($index)">delete</button></td>
		</tr>
	</table>
</div>
<hr>

<div>
	<input type="text" ng-model="cu.uname"><br>
	<input type="number"  ng-model="cu.age"><br>
	<button ng-click="addUser()">addUser</button>
	<button ng-click="confirm()">confirm</button>
</div>

<script>
	
	var mainApp = angular.module("mainApp",[]);
	mainApp.controller('userCtrl',function ($scope,$http) {
		var pointer = 0;
		var req ={
			method:"GET",
			url:"user"
		};
		$http(req).then(function (res) {
					$scope.users = res.data;
		          })
		$scope.edit = function (index) {
			pointer = index;
			$scope.cu = angular.copy($scope.users[index]);
		}

		$scope.delete = function (index) {
			var req = {
				method:"DELETE",
				url:"user/"+$scope.users[index]._id
			}
			$http(req).then(function (res) {
				if(!res.data.error){
					$scope.users.splice(index,1);
				}
			})
		}

		$scope.addUser = function(){
			var req={
				method:"POST",
				url:"user",
				data:$scope.cu,
				headers:{
					"Content-type":"application/json"
				}
			}
			$http(req).then(function(res){
				console.log(res.data);
				$scope.users.push(res.data);
			})
		}
		$scope.confirm = function () {
			var req = {
				method:"PUT",
				url:"user/"+$scope.cu._id,
				data:$scope.cu,
				headers:{
					"Content-type":"application/json"
				}
			}
			$http(req).then(function (res) {
				$scope.users[pointer] = angular.copy($scope.cu);
			})
		}

	})
	
</script>
</body>
</html>